package com.zhb.scanner

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.device.ScanManager
import android.device.scanner.configuration.PropertyID
import androidx.lifecycle.MutableLiveData

/**
 * Created by HongboZhao on 2020/12/22.
 */
class Scanner {

    private val mScanResult by lazy { ScanBroadcastReceiver() }

    fun initialize(context: Context) {
        appContext = context
        //注册广播
        registerReceiver()
        //默认启用后设置广播模式
        resetDataInterface()
    }

    private fun registerReceiver() {
        val filter = IntentFilter()
        filter.addAction(NS5)
        filter.addAction(DT50)
        appContext?.registerReceiver(mScanResult, filter)
    }

    private val barCodeLiveData by lazy { MutableLiveData<String>() }

    fun get(): MutableLiveData<String> {
        resetDataInterface()
        return barCodeLiveData
    }

    /**
     * 每次获取扫码数据都重置扫码模式为广播模式
     */
    fun resetDataInterface(){
        resetScanModel()
        resetScanModelDT()
    }

    /**
     * 配置新大陆扫码模式为广播输出
     */
    private fun resetScanModel() {
        val intent = Intent("ACTION_BAR_SCANCFG")
        intent.putExtra("EXTRA_SCAN_MODE", 3)
        appContext?.sendBroadcast(intent)
    }

    /**
     * 配置优博讯设置扫码模式为广播输出
     */
    private fun resetScanModelDT() {
        try {
            var scanDevice = ScanManager()
            scanDevice.openScanner()
            val idmodebuf = intArrayOf(
                PropertyID.WEDGE_KEYBOARD_ENABLE,
                PropertyID.TRIGGERING_MODES,
                PropertyID.LABEL_APPEND_ENTER
            )
            var idmode = intArrayOf(0, 0, 0)
            scanDevice.setParameterInts(idmodebuf, idmode)
        } catch (e: Exception) {
        }
    }

    companion object {
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { Scanner() }
        var appContext: Context? = null
    }
}